package com.lagou.edu.common.jwt;

import io.jsonwebtoken.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 解析jwt
 */
@Slf4j
public final class JwtUtil {
    private static final String X_USER_ID = "user_id";
    private static final String X_USER_NAME = "user_name";

    public static JwtResult parse(String signKey, String jwtToken) {
        try {
            Jws<Claims> jwt = Jwts.parser()
                    .setSigningKey(signKey.getBytes())
                    .parseClaimsJws(jwtToken);
            if (null != jwt && null != jwt.getBody()) {
                Integer userId = jwt.getBody().get(X_USER_ID, Integer.class);
                String userName = jwt.getBody().get(X_USER_NAME, String.class);
                return new JwtResult(userId, userName);
            }
        } catch (ExpiredJwtException | MalformedJwtException | SignatureException e) {
            log.error("user token error :{}", e.getMessage());
        }
        return new JwtResult();
    }

    public static String createToken(String sign) {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.set(Calendar.YEAR,2099);
        Date expiresDate = nowTime.getTime();

        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", 100030018);
        map.put("user_name", "tom");

        // build token
        // param backups {iss:Service, aud:APP}
        String token = Jwts.builder()
                .addClaims(map)
                .setId("1")
                .signWith(SignatureAlgorithm.HS256,new String(Base64.encodeBase64(sign.getBytes())))

                .setIssuedAt(iatDate) // sign time
                .setExpiration(expiresDate).compact(); // expire time

        return token;
    }


    public static void main(String[] args) {
        String s = "123456";

        String token = createToken(s);
        System.out.println(token    );
        Jws<Claims> jwt = Jwts.parser()
                .setSigningKey(new String(Base64.encodeBase64(s.getBytes())))
                .parseClaimsJws(token);
        Claims body = jwt.getBody();
        System.out.println(body.get("user_id"));
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class JwtResult {
        private Integer userId;
        private String userName;
    }
}
